package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

@Configuration
public class MyMessageConvery {

    private RabbitTemplate rabbitTemplate;


    @Bean
    public MessageConverter getMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    //在MyMessageConvery初始化的时候调用init方法

    @Bean
    @Primary
    public RabbitTemplate getRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(getMessageConverter());
        //初始化
        init();
        return rabbitTemplate;

    }


    //    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData   关联消息的唯一性，在消息发送的时候可以指定correlationData
             * @param ack  是否到达服务器
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("correlationData:[" + correlationData + "]==>,ack:[" + ack + "]==>,cause:[" + cause + "]");
            }
        });
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             *
             * @param message 失败的消息
             * @param replyCode  失败返回的code码
             * @param replyText  失败返回的文本内容
             * @param exchange    发送失败的交换机
             * @param routingKey  路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("message:==>[" + message + "],replyText:==>[" + replyText + "],replyCode==>[" + replyCode + "],routingKey==>[" + routingKey + "]");
            }
        });

        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());

    }


}
